package mytest.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import mytest.util.RequestUtil;
import mytest.util.Response;
import test.testcase.dao.preurlDao;
import test.utils.JsonResult;

@Controller @RequestMapping(value = "/preurl", produces = "application/json; charset=utf-8")
@CrossOrigin
public class preurl {
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody String getlist(HttpServletRequest request) {
		return preurlDao.getList(RequestUtil.getStartPage(request), RequestUtil.getEndPage(request), RequestUtil.getProjectId(request)).toResponse();
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody String add(@RequestBody String body, HttpServletRequest request) {
		JsonResult result = JsonResult.parse(body);
		String projectid = RequestUtil.getProjectId(request);
		if (projectid == null || projectid.equals("")) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("请选择项目");
			return response.toString();
		}
		return preurlDao.add(projectid, result.read("projectname").toString(), result.read("url").toString()).toResponse();
	}
	
	@RequestMapping(value = "/del/{projectname}/{projectid}", method = RequestMethod.GET)
	public @ResponseBody String del(@PathVariable String projectname, @PathVariable String projectid) {
		JsonResult result = preurlDao.del(projectname, projectid);
		if (result == null) {
			Response response = new Response();
			response.setRetCodeFalse();
			response.setRetMessage("项目不能删除，因为有用例等依赖");
			return response.toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/info/{projectname}/{projectid}", method = RequestMethod.GET)
	public @ResponseBody String getinfo(@PathVariable String projectid, @PathVariable String projectname) {
		return preurlDao.getInfo(projectid, projectname).toResponse();
	}
	
	@RequestMapping(value = "/save/{projectname}/{projectid}", method = RequestMethod.POST)
	public @ResponseBody String save(@PathVariable String projectid, @RequestBody String body, @PathVariable String projectname) {
		JsonResult result = JsonResult.parse(body);
		String preurl = result.read("url").toString();
		return preurlDao.save(projectid, projectname, preurl).toResponse();
	}
	
}
